//
//  Preferences.swift
//  SitPosition
//
//  Created by apple on 2019/1/6.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation


struct Preferences {
    
    private static let store: UserDefaults = UserDefaults.standard
    
    // app启动时调用一次
    public static func onAppLaunch() {
        let defaults: [String : Any] = [
            keyofUserRole: UserRole.student.rawValue
        ]
        store.register(defaults: defaults)
    }
    
    // 最后一次登录的身份角色
    static private let keyofUserRole: String = "userRole"
    static var userRole: UserRole {
        get {
            if let s = store.string(forKey: Preferences.keyofUserRole) {
                return UserRole(rawValue: s) ??
                UserRole.student
            } else {
                return UserRole.student
            }
        }
        set {
            store.setValue(newValue.rawValue, forKey: keyofUserRole)
        }
    }
    
    // 身体倾斜
    static private let keyofBodySlantThreshold: String = "bodySlantThreshold"
    static var bodySlantThreshold: Int? {
        get {
            let value = store.integer(forKey: keyofBodySlantThreshold)
            if value == 0 {
                return nil
            }
            return value
        }
        set { store.setValue(newValue, forKey: keyofBodySlantThreshold) }
    }
    
    static private let keyofHeadLowUpThreshold: String = "headLowUp"
    static var headLowUpThreshold: Int? {
        get {
            let value = store.integer(forKey: keyofHeadLowUpThreshold)
            if value == 0 {
                return nil
            }
            return value
        }
        set { store.setValue(newValue, forKey: keyofHeadLowUpThreshold) }
    }
    
    static private let keyofHeadLeftThreshold: String = "headLeft"
    static var headLeftThreshold: Int? {
        get {
            let value = store.integer(forKey: keyofHeadLeftThreshold)
            if value == 0 {
                return nil
            }
            return value
        }
        set { store.setValue(newValue, forKey: keyofHeadLeftThreshold) }
    }
    
    static private let keyofHeadRightThreshold: String = "headRight"
    static var headRightThreshold: Int? {
        get {
            let value = store.integer(forKey: keyofHeadRightThreshold)
            if value == 0 {
                return nil
            }
            return value
        }
        set { store.setValue(newValue, forKey: keyofHeadRightThreshold) }
    }
    
    static private let keyofHeadRotateThreshold: String = "headRotate"
    static var headRotateThreshold: Int? {
        get {
            let value = store.integer(forKey: keyofHeadRotateThreshold)
            if value == 0 {
                return nil
            }
            return value
        }
        set { store.setValue(newValue, forKey: keyofHeadRotateThreshold) }
    }
}
